<template>
  <div class="item-dialog-select">
    <!-- 触发选择器 -->
    <div class="item-select-wrapper" @click="openDialog" :class="{ disabled: disabled }">
      <div class="select-input">
        <!-- 选择框前缀图标 -->
        <el-icon class="prefix-icon"><Collection /></el-icon>

        <!-- 已选项目展示 -->
        <div class="selected-content">
          <div v-if="!selectedItem" class="placeholder-text">
            {{ placeholder }}
          </div>
          <div v-else class="selected-item">
            <span class="item-text">{{ selectedItem.name }}</span>
          </div>
        </div>

        <!-- 下拉箭头 -->
        <el-icon class="suffix-icon"><ArrowDown /></el-icon>
      </div>
    </div>

    <!-- 项目选择弹窗 -->
    <common-dialog-select
      ref="dialogRef"
      :title="dialogTitle"
      :width="dialogWidth"
      :columns="columns"
      :request-api="loadItemList"
      :search-col="searchCol"
      :init-param="initParam"
      @change="handleSelectionChange"
    />
  </div>
</template>

<script setup lang="ts" name="ItemDialogSelect">
import { ref, computed, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import { Collection, ArrowDown } from "@element-plus/icons-vue";
import { useDataStore } from "@/stores/modules/data";
import apiService from "@/api/services/apiService";
import commonDialogSelect from "./common-dialog-select.vue";
import { ColumnProps } from "@/components/ProTable/interface";

interface Item {
  _id: string;
  item_no: string;
  name: string;
  year: string;
  level: string;
  state: string;
  [key: string]: any;
}

// Props定义
interface SelectProps {
  modelValue?: string;
  placeholder?: string;
  disabled?: boolean;
  dialogTitle?: string;
  dialogWidth?: string;
}

const props = withDefaults(defineProps<SelectProps>(), {
  placeholder: "请选择项目",
  dialogTitle: "选择项目",
  dialogWidth: "800px"
});

// Emit定义
const emit = defineEmits<{
  (e: "update:modelValue", value: string | undefined): void;
  (e: "change", value: Item | undefined): void;
}>();

// 响应式数据
const dialogRef = ref<InstanceType<typeof commonDialogSelect> | null>(null);
const selectedItem = ref<Item | null>(null);
const initParam = ref({});

// 数据存储
const dataStore = useDataStore();

// 表格列配置
const columns = ref<ColumnProps<Item>[]>([
  { prop: "item_no", label: "项目编号", width: 120 },
  { prop: "name", label: "项目名称", search: { el: "input" } },
  { prop: "year", label: "年度", width: 80 },
  {
    prop: "level",
    label: "项目级别",
    width: 100,
    enum: computed(() => dataStore.getEnumByCsName("ITEM_LEVEL") || []),
    fieldNames: { label: "name", value: "_id" }
  },
  {
    prop: "state",
    label: "状态",
    width: 100,
    enum: computed(() => dataStore.getEnumByCsName("ITEM_STATE") || []),
    fieldNames: { label: "name", value: "_id" }
  }
]);

// 搜索配置
const searchCol = ref({
  xs: 1,
  sm: 1,
  md: 2,
  lg: 3,
  xl: 3
});

// 处理选择变化
const handleSelectionChange = (selection: { [key: string]: any }[] | undefined) => {
  if (selection && selection.length > 0) {
    const selected = selection[0] as Item;
    selectedItem.value = selected;
    emit("update:modelValue", selected._id);
    emit("change", selected);
  } else {
    selectedItem.value = null;
    emit("update:modelValue", undefined);
    emit("change", undefined);
  }
};

// 打开弹窗
const openDialog = () => {
  if (props.disabled) return;
  // 设置初始化参数
  initParam.value = selectedItem.value ? { selectedId: selectedItem.value._id } : {};
  dialogRef.value?.openDialog();
};

// 加载项目列表
const loadItemList = async (params: any = {}) => {
  try {
    // 构建查询条件
    const condition: any = {};

    // 处理名称搜索
    if (params.name) {
      condition.name = { $like: params.name };
    }

    // 处理状态筛选
    if (params.state) {
      condition.state = params.state;
    }

    const query = {
      condition,
      options: { sort: { create_at: -1 } }
    };

    return apiService.find<Item>("item", query.condition, query.options);
  } catch (error) {
    console.error("加载项目列表失败:", error);
    ElMessage.error("加载项目列表失败");
  }
};

// 根据ID加载单个项目信息
const loadItemById = async (id: string) => {
  try {
    const res = await apiService.findOne<Item>("item", { _id: id });
    if (res.data) {
      selectedItem.value = res.data;
    }
  } catch (error) {
    console.error("加载项目信息失败:", error);
    ElMessage.error("加载项目信息失败");
  }
};

// 监听modelValue变化
watch(
  () => props.modelValue,
  (newVal, oldVal) => {
    if (newVal !== oldVal) {
      if (newVal) {
        // 如果有新值但selectedItem不匹配，则需要重新加载数据并设置选中项
        if (!selectedItem.value || selectedItem.value._id !== newVal) {
          loadItemById(newVal);
        }
      } else {
        selectedItem.value = null;
      }
    }
  },
  { immediate: true }
);

// 组件挂载时加载枚举数据
onMounted(() => {
  dataStore.findEnumByCsName("ITEM_LEVEL");
  dataStore.findEnumByCsName("ITEM_STATE");
});

// 暴露方法
defineExpose({
  openDialog
});
</script>

<style scoped lang="scss">
.item-dialog-select {
  width: 100%;
  .item-select-wrapper {
    width: 100%;
    height: 32px;
    cursor: pointer;
    background-color: var(--el-fill-color-blank);
    border: 1px solid var(--el-border-color);
    border-radius: var(--el-border-radius-base);
    transition: var(--el-transition-border);
    &:hover:not(.disabled) {
      border-color: var(--el-color-primary);
    }
    &.disabled {
      cursor: not-allowed;
      background-color: var(--el-disabled-bg-color);
    }
    .select-input {
      display: flex;
      align-items: center;
      height: 100%;
      padding: 0 10px;
      .prefix-icon {
        margin-right: 8px;
        color: var(--el-text-color-placeholder);
      }
      .selected-content {
        flex: 1;
        overflow: hidden;
        text-overflow: ellipsis;
        white-space: nowrap;
        .placeholder-text {
          overflow: hidden;
          font-size: var(--el-font-size-base);
          color: var(--el-text-color-placeholder);
          text-overflow: ellipsis;
          white-space: nowrap;
        }
        .selected-item {
          overflow: hidden;
          font-size: var(--el-font-size-base);
          color: var(--el-text-color-regular);
          text-overflow: ellipsis;
          white-space: nowrap;
          .item-text {
            overflow: hidden;
            font-size: var(--el-font-size-base);
            color: var(--el-text-color-regular);
            text-overflow: ellipsis;
            white-space: nowrap;
          }
        }
      }
      .suffix-icon {
        margin-left: 8px;
        color: var(--el-text-color-placeholder);
        transition: transform 0.3s;
      }
    }
  }
}
</style>
